package com.szosen.util;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PRIndirectReference;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.measurement.MeasureECGActivity;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;

public class FileSaveUtil {
    private static String sdState = Environment.getExternalStorageState();
    private static String path = Environment.getExternalStorageDirectory()
            .toString();
    private static String manbingPath = path;
    //健康档案目录名称
    private static final String DirectoryName_jkda = "健康档案打印目录";
    //健康体检目录名称
    private static final String DirectoryName_jktj = "健康体检打印目录";
    //心电报告目录名称
    private static final String DirectoryName_ecg = "心电报告打印目录";
    //测量记录目录名称
    private static final String DirectoryName_cljl = "测量记录打印目录";
    private static final String DirectoryName_shzl = "自理能力打印目录";
    private static final String DirectoryName_zytzbs = "中医体质辨识打印目录";

    /**
     * 批量打印。获取健康档案的内部存储的主目录
     */
    public static String getPrintPath_JKDA() {
        return getSDCardPath() + DirectoryName_jkda;
    }

    /**
     * 批量打印。获取健康体检的内部存储的主目录
     */
    public static String getPrintPath_JKTJ() {

        return getSDCardPath() + DirectoryName_jktj;
    }

    /**
     * 批量打印。获取心电报告的内部存储的主目录
     */
    public static String getPrintPath_ECG() {

        return getSDCardPath() + DirectoryName_ecg;
    }

    /**
     * 批量打印。获取测量记录的内部存储的主目录
     */
    public static String getPrintPath_CLJL() {

        return getSDCardPath() + DirectoryName_cljl;
    }

    /**
     * 批量打印。获取测量记录的内部存储的主目录
     */
    public static String getPrintPath_SHZL() {

        return getSDCardPath() + DirectoryName_shzl;
    }

    /**
     * 批量打印。获取测量记录的内部存储的主目录
     */
    public static String getPrintPath_ZYTZBS() {

        return getSDCardPath() + DirectoryName_zytzbs;
    }

    /***
     * 复制文件夹
     * @param path
     * @param copyPath
     * @throws IOException
     */
    public static void copyDirectory(String path, String copyPath) throws IOException {
//        System.out.println("方法copyDirectory，path=" + path + ",copyPath=" + copyPath);
        File filePath = new File(path);
        if (!filePath.exists()) {
            boolean b = filePath.mkdirs();
        }
        DataInputStream read;
        DataOutputStream write;
        if (filePath.isDirectory()) {
            File[] list = filePath.listFiles();
            for (int i = 0; i < list.length; i++) {
                String newPath = path + File.separator + list[i].getName();
                String newCopyPath = copyPath + File.separator + list[i].getName();
                File newFile = new File(copyPath);
                File newCopyPathFile = new File(newCopyPath);
                if (!newFile.exists()) {
                    if (newFile.isDirectory()) {
                        boolean b = newFile.mkdir();
                    } else if (newFile.isFile()) {
                        boolean c = newFile.createNewFile();
                    }
                }
                if (!newCopyPathFile.exists()) {
                    if (newCopyPathFile.isDirectory()) {
                        boolean b = newCopyPathFile.mkdir();
                    } else if (newCopyPathFile.isFile()) {
                        boolean b = newCopyPathFile.createNewFile();
                    }
                }
                copyDirectory(newPath, newCopyPath);
            }
        } else if (filePath.isFile()) {
            read = new DataInputStream(new BufferedInputStream(new FileInputStream(path)));
            if (!filePath.exists()) {
                filePath.createNewFile();
            }
            File newFile = new File(copyPath);
            File parentFile = newFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            if (!newFile.exists()) {
                newFile.createNewFile();
            } else {
                newFile.delete();
            }
            write = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(copyPath)));
            byte[] buf = new byte[1024 * 512];
            while (read.read(buf) != -1) {
                write.write(buf);
            }
            read.close();
            write.close();
        } else {
            System.out.println("请输入正确的文件名或路径名");
        }
    }

    /***
     * 返回sd卡的文件夹名字
     * 村医版
     *
     * @return
     */
    public static String getSDCardName() {
        return MeasureECGActivity.FileName;
    }

    /***
     * 返回sd卡的路径位置
     *
     * @return
     */
    public static String getSDCardPath() {
        return path + "/" + MeasureECGActivity.FileName + "/";
    }

    /***
     *
     *            是高血压还是糖尿病
     * @param pathName
     * @param fileName
     * @param fileContent
     */
    public static File saveTxtFile(String pathName, String fileName,
                                   String fileContent) {
        File file;
        File mainFile = null;
        if (sdState.equals(Environment.MEDIA_MOUNTED)) {
            // 获得sd卡根目录
            file = new File(manbingPath, "/" + MeasureECGActivity.FileName
                    + "/" + pathName);
            if (!file.exists()) {
                file.mkdirs();
            }
            mainFile = new File(file, fileName + ".txt");
            try {
                if (!mainFile.exists()) {
                    mainFile.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(mainFile);
                // System.out.println("fileSaveUtil。savetxtfile内容"+fileContent);
                fos.write(fileContent.getBytes());
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mainFile;
    }

    public static void saveUserListTxtFile(String pathName, String fileName,
                                           String fileContent) {
        // File file;
        // File mainFile;
        // if (sdState.equals(Environment.MEDIA_MOUNTED)) {
        // // 获得sd卡根目录
        // file = new File(manbingPath, "/新达启帆/"+pathName);
        // if (!file.exists()) {
        // file.mkdirs();
        // }
        // mainFile = new File(file, fileName + ".txt");
        // try {
        // if (!mainFile.exists()) {
        // mainFile.createNewFile();
        // }
        // FileOutputStream fos = new FileOutputStream(mainFile);
        // System.out.println(fileContent);
        // fos.write(fileContent.getBytes());
        // fos.flush();
        // fos.close();
        // } catch (FileNotFoundException e) {
        // e.printStackTrace();
        // } catch (IOException e) {
        // e.printStackTrace();
        // }
        // }
    }

    // 将SD卡文件删除
    public static void deleteFile(File file) {
        if (sdState.equals(Environment.MEDIA_MOUNTED)) {
            if (file.exists()) {
                if (file.isFile()) {
                    file.delete();
                }
                // 如果它是一个目录
                else if (file.isDirectory()) {
                    // 声明目录下所有的文件 files[];
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                        deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
                    }
                }
                file.delete();
            }
        }
    }

    /***
     * 保存pdf文件打印
     *
     * @param context
     * @param headContent
     *            头的内容
     * @param resultContent
     *            返回的心电诊断结论
     * @param pngPath
     *            图片缓存地址
     * @param filePath
     *            文件目录
     */
    public static void savePDFFile(final Context context,
                                   final String headContent, final String resultContent,
                                   final String pngPath, final String filePath, final String time) {
        new Thread() {
            public void run() {
                Document document = new Document(PageSize.A4.rotate(), 25, 20,
                        10, 10);
                try {
                    File pdfFile = new File(filePath);
                    FileOutputStream fos = new FileOutputStream(pdfFile);
                    PdfWriter.getInstance(document, fos);
                    // 打开document
                    document.open();
                    // 添加字体文件
                    BaseFont baseFontChinese = BaseFont.createFont(
                            "STSong-Light", "UniGB-UCS2-H",
                            BaseFont.NOT_EMBEDDED);
                    Font fontChinese = new Font(baseFontChinese, 14,
                            Font.NORMAL);
                    Chunk timeChunk = new Chunk(time, fontChinese);
                    // timeChunk.set
                    String birthday = BaseActivity.getHealthRecord()
                            .getBirthday();
                    int old = 0;
                    if (birthday.length() > 4) {
                        int now = Integer.valueOf(Tools.GetCurrentTime()
                                .substring(0, 4));
                        int bir = Integer.valueOf(birthday.substring(0, 4));
                        old = now - bir;
                    }
                    String sexCode = BaseActivity.getHealthRecord()
                            .getSexCode();
                    if ("1".equals(sexCode)) {
                        sexCode = "男";
                    } else if ("2".equals(sexCode)) {
                        sexCode = "女";
                    }
                    Paragraph head = new Paragraph(" 姓名： " + headContent
                            + "    性别：    " + sexCode + "    年龄：   "
                            + (old == 0 ? "" : "" + old).replace("+", "")
                            + "\n", fontChinese);
                    Paragraph result = new Paragraph(resultContent + "\n",
                            fontChinese);
                    Paragraph title = new Paragraph("心电诊断报告\n", new Font(
                            baseFontChinese, 16, Font.NORMAL));
                    Paragraph printTime = new Paragraph("打印时间："
                            + TimeHelper.getCurrentTime(), new Font(
                            baseFontChinese, 8, Font.NORMAL));
                    Paragraph doctor = new Paragraph(
                            "医生签名：                       ", new Font(
                            baseFontChinese, 16, Font.NORMAL));
                    printTime.setAlignment(Element.ALIGN_RIGHT);
                    doctor.setAlignment(Element.ALIGN_RIGHT);
                    title.setAlignment(Element.ALIGN_CENTER);// 居中显示
                    //
                    // 添加了图片
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    Bitmap bitmap = BitmapFactory
                            .decodeStream(new FileInputStream(new File(pngPath)));
                    Bitmap bitmap2 = small(bitmap);
                    document.setPageCount(1);
                    bitmap2.compress(Bitmap.CompressFormat.PNG /* FileType */,
                            100 /* Ratio */, stream);
                    Image jpg = Image.getInstance(stream.toByteArray());
                    //
                    AssetManager assetManager = context.getAssets();
                    InputStream is = assetManager.open("asign.png");
                    Bitmap asign = BitmapFactory.decodeStream(is);
                    Bitmap asign2 = small(asign, 0.15f, 0.15f);
                    ByteArrayOutputStream asignStream = new ByteArrayOutputStream();
                    asign2.compress(Bitmap.CompressFormat.PNG /* FileType */,
                            100 /* Ratio */, asignStream);
                    Image asignJpg = Image.getInstance(asignStream
                            .toByteArray());
                    // asign2.getWidth();
                    asignJpg.setAbsolutePosition(document.getPageSize()
                            .getWidth() - asign2.getWidth(), 0);
                    //
                    document.add(title);
                    document.add(head);
                    document.add(jpg);
                    document.add(printTime);
                    document.add(result);
                    document.add(asignJpg);
                    document.close();
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Intent intent = new Intent();
                    // ComponentName comp = new ComponentName(
                    // "com.dynamixsoftware.printershare",
                    // "com.dynamixsoftware.printershare.ActivityPrintPDF");
                    // intent.setComponent(comp);
                    intent.setAction("android.intent.action.VIEW");
                    intent.setDataAndType(Uri.fromFile(pdfFile),
                            "application/msword");
                    context.startActivity(intent);
                } catch (Exception e) {
                    System.out.println("保存打印文件失败。。。");
                    e.printStackTrace();
                } finally {

                }
            }

            ;
        }.start();

    }

    public static void testpdf(Context context) {
        Document document = new Document(PageSize.A4.rotate(), 25, 20, 10, 10);
        try {
            File pdfFile = new File(getSDCardPath(), "caonima.pdf");
            FileOutputStream fos = new FileOutputStream(pdfFile);
            PdfWriter.getInstance(document, fos);
            // 打开document
            document.open();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(
                    new File(getSDCardPath() + "/心电打印文档图片缓存/TT",
                            "2016-11-18T17+52+15.00.png")));
            document.setPageCount(1);
            bitmap.compress(Bitmap.CompressFormat.PNG /* FileType */,
                    100 /* Ratio */, stream);
            Image jpg = Image.getInstance(stream.toByteArray());
            document.add(jpg);
            document.close();
            Intent intent = new Intent();
            // ComponentName comp = new ComponentName(
            // "com.dynamixsoftware.printershare",
            // "com.dynamixsoftware.printershare.ActivityPrintPDF");
            // intent.setComponent(comp);
            intent.setAction("android.intent.action.VIEW");
            intent.setDataAndType(Uri.fromFile(pdfFile), "application/msword");
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 保存一张尿液的pdf。写到文字中。
     */
    public static void saveNiaoyePdf(Context context, String pdfPath,
                                     String pdfName, String name, String sex, String yearsold,
                                     String checkTime, String glu, String leu, String bld, String ph,
                                     String pro, String ubg, String nit, String sg, String ket,
                                     String bil, String vc) {
        // 先打开document，然后获取文件流
        Document document = new Document(PageSize.A4);
        document.setPageCount(1);
        try {
            File pdfPathFile = new File(pdfPath);
            if (!pdfPathFile.exists()) {
                pdfPathFile.mkdirs();
            }
            File pdfFile = new File(pdfPathFile, pdfName);
            if (!pdfFile.exists()) {
                pdfFile.createNewFile();
            }
            PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
            document.open();
            // 设置标题头
            Paragraph title = new Paragraph("尿液分析报告\n", getChineseFont(18));
            title.setAlignment(Element.ALIGN_CENTER);// 居中显示
            // 增加病人信息
            document.add(title);
            Paragraph userInfo = new Paragraph("  姓名： " + name + "  性别：    "
                    + sex + "  年龄：" + yearsold + "\n", getChineseFont(16));
            document.add(userInfo);
            document.add(new Paragraph("", getChineseFont(2)));
            // 增加尿液测量的项目参数、数据
            int cellCount = 6;
            PdfPTable table = getNiaoyetable(cellCount);
            Font font = getChineseFont(14);
            table.addCell(new Paragraph("序号", font));
            table.addCell(new Paragraph("英文代号", font));
            table.addCell(new Paragraph("项目", font));
            table.addCell(new Paragraph("结果", font));
            table.addCell(new Paragraph("单位", font));
            table.addCell(new Paragraph("参考值", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("1", font));
            table.addCell(new Paragraph("glu", font));
            table.addCell(new Paragraph("尿糖", font));
            table.addCell(new Paragraph(glu, font));
            table.addCell(new Paragraph("mmol/L", font));
            // 单位
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("2", font));
            table.addCell(new Paragraph("leu", font));
            table.addCell(new Paragraph("白细胞", font));
            table.addCell(new Paragraph(leu, font));
            table.addCell(new Paragraph("Cell/uL", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("3", font));
            table.addCell(new Paragraph("bld", font));
            table.addCell(new Paragraph("潜血", font));
            table.addCell(new Paragraph(bld, font));
            table.addCell(new Paragraph("", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("4", font));
            table.addCell(new Paragraph("ph", font));
            table.addCell(new Paragraph("酸碱度", font));
            table.addCell(new Paragraph(ph, font));
            table.addCell(new Paragraph("ph", font));
            table.addCell(new Paragraph("6.5-7.5", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("5", font));
            table.addCell(new Paragraph("pro", font));
            table.addCell(new Paragraph("蛋白质", font));
            table.addCell(new Paragraph(pro, font));
            table.addCell(new Paragraph("g/L", font));
            table.addCell(new Paragraph("6.5-7.5", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("6", font));
            table.addCell(new Paragraph("ubg", font));
            table.addCell(new Paragraph("尿胆原", font));
            table.addCell(new Paragraph(ubg, font));
            table.addCell(new Paragraph("umol/L", font));
            table.addCell(new Paragraph("3-16umol/L", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("7", font));
            table.addCell(new Paragraph("nit", font));
            table.addCell(new Paragraph("亚硝酸盐", font));
            table.addCell(new Paragraph(nit, font));
            table.addCell(new Paragraph("", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("8", font));
            table.addCell(new Paragraph("sg", font));
            table.addCell(new Paragraph("比重", font));
            table.addCell(new Paragraph(sg, font));
            table.addCell(new Paragraph("", font));
            table.addCell(new Paragraph("1.003-1.03", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("9", font));
            table.addCell(new Paragraph("ket", font));
            table.addCell(new Paragraph("尿酮体", font));
            table.addCell(new Paragraph(ket, font));
            table.addCell(new Paragraph("mmol/L", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("10", font));
            table.addCell(new Paragraph("bil", font));
            table.addCell(new Paragraph("胆红素", font));
            table.addCell(new Paragraph(bil, font));
            table.addCell(new Paragraph("umol/L", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("11", font));
            table.addCell(new Paragraph("vc", font));
            table.addCell(new Paragraph("维生素C", font));
            table.addCell(new Paragraph(vc, font));
            table.addCell(new Paragraph("mmol/L", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);
            Paragraph time = new Paragraph("测量时间：" + checkTime, font);
            time.setAlignment(Element.ALIGN_RIGHT);
            document.add(time);
            document.close();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Intent intent = new Intent();
            // ComponentName comp = new ComponentName(
            // "com.dynamixsoftware.printershare",
            // "com.dynamixsoftware.printershare.ActivityPrintPDF");
            // intent.setComponent(comp);
            intent.setAction("android.intent.action.VIEW");
            intent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf");
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    /***
     * 保存一张尿液的bitmap图片。。写到文字中。
     */
    public static boolean saveNiaoyeBitmap(Context context, String bitmapPath,
                                           String bitmapName, String idCard, String hospitalName, String name,
                                           String sex, String yearsold, String checkTime, String glu,
                                           String leu, String bld, String ph, String pro, String ubg,
                                           String nit, String sg, String ket, String bil, String vc) {
        Bitmap bitmap = Bitmap
                .createBitmap(1758, 2500, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        int startY = 220;
        int startX = 200;
        // 分别保存尿液、血压、血糖到一张纸上。
        startY = drawUserInfo(canvas, startX, startY, name, sex, yearsold,
                hospitalName, idCard);
        drawNiaoye(canvas, startX, startY, name, sex, yearsold, checkTime, glu,
                leu, bld, ph, pro, ubg, nit, sg, ket, bil, vc);
        return saveBitmap(bitmap, bitmapPath, bitmapName);
    }

    public static int drawUserInfo(Canvas canvas, int startX, int startY,
                                   String name, String sex, String yearsold, String hospitalName,
                                   String idCard) {
        // 字体
        Paint textPaint = new Paint();
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL);
        int textSize = 48;
        textPaint.setTextSize(textSize);
        textPaint.setColor(color_title);
        // 将身份号替换月日为****
        idCard = idCard.substring(0, idCard.length() - 8) + "****"
                + idCard.substring(idCard.length() - 4, idCard.length());
        canvas.drawText("姓名：" + name + "  性别：" + sex + "  年龄：" + yearsold
                + "  身份证：" + idCard, startX, startY, textPaint);
        startY += textSize;
        canvas.drawText("医院名称：" + hospitalName, startX, startY, textPaint);
        startY += textSize;
        startY += textSize;
        return startY;
    }

    /***
     * 在画纸上画尿液
     *
     * @param canvas
     */
    public static int drawNiaoye(Canvas canvas, int startX, int startY,
                                 String name, String sex, String yearsold, String checkTime,
                                 String glu, String leu, String bld, String ph, String pro,
                                 String ubg, String nit, String sg, String ket, String bil, String vc) {
        int allWidth = canvas.getWidth();
        int allHeight = canvas.getHeight();
        int titleSize = 60;
        // 字体
        Paint textPaint = new Paint();
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setTextSize(titleSize);
        textPaint.setColor(color_title);
        Paint linePaint = new Paint();
        int lineWidth = 2;
        linePaint.setStrokeWidth(lineWidth);
        linePaint.setColor(color_title);
        startY += titleSize;
        int textSize = 48;
        int marginLeft = startX;
        int marginRight = startX;
        // 格子一个上下的距离
        int textMargin = 5;
        int jiangeY = textSize + textMargin;
        int endX = allWidth - 200;
        int jiangeX = (endX - startX) / 6;
        textPaint.setTextSize(textSize);
        String title = "尿液分析报告";
        textPaint.setTextSize(titleSize);
        canvas.drawText(title, allWidth / 2 - (titleSize * title.length() / 2),
                startY, textPaint);
        startY += titleSize;
        int shuxianStartY = startY;
        textPaint.setTextSize(textSize);
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        // 这里先从上往下话竖线
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += textSize;
        canvas.drawText("序号", startX, startY, textPaint);
        canvas.drawText("英文代号", startX + jiangeX, startY, textPaint);
        canvas.drawText("项目", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText("结果", startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("单位", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("参考值", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        canvas.drawText("1", startX, startY, textPaint);
        canvas.drawText("glu", startX + jiangeX, startY, textPaint);
        canvas.drawText("尿糖", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(glu, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("mmol/L", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("-", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        canvas.drawText("2", startX, startY, textPaint);
        canvas.drawText("leu", startX + jiangeX, startY, textPaint);
        canvas.drawText("白细胞", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(leu, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("Cell/L", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("-", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        //
        canvas.drawText("3", startX, startY, textPaint);
        canvas.drawText("bld", startX + jiangeX, startY, textPaint);
        canvas.drawText("潜血", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(bld, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("-", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        //
        canvas.drawText("4", startX, startY, textPaint);
        canvas.drawText("ph", startX + jiangeX, startY, textPaint);
        canvas.drawText("酸碱度", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(ph, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("ph", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("6.5-7.0", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        //
        canvas.drawText("5", startX, startY, textPaint);
        canvas.drawText("pro", startX + jiangeX, startY, textPaint);
        canvas.drawText("蛋白质", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(pro, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("g/L", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("6.5-7.5", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        //
        canvas.drawText("6", startX, startY, textPaint);
        canvas.drawText("ubg", startX + jiangeX, startY, textPaint);
        canvas.drawText("尿胆原", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(ubg, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("umol/L", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("3-16", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        //
        canvas.drawText("7", startX, startY, textPaint);
        canvas.drawText("nit", startX + jiangeX, startY, textPaint);
        canvas.drawText("亚硝酸盐", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(nit, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("-", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        //
        canvas.drawText("8", startX, startY, textPaint);
        canvas.drawText("sg", startX + jiangeX, startY, textPaint);
        canvas.drawText("比重", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(sg, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("1.003-1.03", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        //
        canvas.drawText("9", startX, startY, textPaint);
        canvas.drawText("ket", startX + jiangeX, startY, textPaint);
        canvas.drawText("尿酮体", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(ket, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("mmol/L", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("-", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        //
        canvas.drawText("10", startX, startY, textPaint);
        canvas.drawText("bil", startX + jiangeX, startY, textPaint);
        canvas.drawText("胆红素", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(bil, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("umol/L", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("-", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        startY += jiangeY;
        //
        canvas.drawText("11", startX, startY, textPaint);
        canvas.drawText("vc", startX + jiangeX, startY, textPaint);
        canvas.drawText("维生素C", startX + jiangeX * 2, startY, textPaint);
        canvas.drawText(vc, startX + jiangeX * 3, startY, textPaint);
        canvas.drawText("mmol/L", startX + jiangeX * 4, startY, textPaint);
        canvas.drawText("-", startX + jiangeX * 5, startY, textPaint);
        startY += textMargin;
        canvas.drawLine(startX, startY, endX, startY, linePaint);
        int shuxian_endY = startY;
        canvas.drawLine(startX, shuxianStartY, startX, shuxian_endY, linePaint);
        canvas.drawLine(startX + jiangeX, shuxianStartY, startX + jiangeX,
                shuxian_endY, linePaint);
        canvas.drawLine(startX + jiangeX * 2 - 10, shuxianStartY, startX
                + jiangeX * 2 - 10, shuxian_endY, linePaint);
        canvas.drawLine(startX + jiangeX * 3 - 10, shuxianStartY, startX
                + jiangeX * 3 - 10, shuxian_endY, linePaint);
        canvas.drawLine(startX + jiangeX * 4 - 10, shuxianStartY, startX
                + jiangeX * 4 - 10, shuxian_endY, linePaint);
        canvas.drawLine(startX + jiangeX * 5 - 10, shuxianStartY, startX
                + jiangeX * 5 - 10, shuxian_endY, linePaint);
        canvas.drawLine(startX + jiangeX * 6 + 2, shuxianStartY, startX
                + jiangeX * 6 + 2, shuxian_endY, linePaint);
        startY += jiangeY;
        textPaint.setTextSize(38);
        canvas.drawText("测量时间：" + checkTime, startX, startY, textPaint);
        startY += jiangeY;
        startY += jiangeY;
        startY += jiangeY;
        return startY;
    }

    public static int drawTiwen(Canvas canvas, int startX, int startY,
                                String temp, String tempTime) {
        int allWidth = canvas.getWidth();
        int allHeight = canvas.getHeight();
        Paint textPaint = new Paint();
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL);
        int titleSize = 60;
        int textSize = 48;
        textPaint.setTextSize(titleSize);
        textPaint.setColor(color_title);
        String title = "体温测量报告";
        canvas.drawText(title, allWidth / 2 - (titleSize * title.length() / 2),
                startY, textPaint);
        startY += titleSize;
        textPaint.setTextSize(textSize);
        canvas.drawText("体温值：" + temp + "℃", startX, startY, textPaint);
        startY += textSize;
        textPaint.setTextSize(38);
        canvas.drawText("测量时间：" + tempTime, startX, startY, textPaint);
        startY += textSize;
        startY += textSize;
        startY += textSize;
        return startY;
    }

    public static int drawXueya(Canvas canvas, int startX, int startY,
                                String sbp, String dbp, String pulse, String xueyaTime, String hand) {
        int allWidth = canvas.getWidth();
        int allHeight = canvas.getHeight();
        Paint textPaint = new Paint();
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL);
        int titleSize = 60;
        int textSize = 48;
        textPaint.setTextSize(titleSize);
        textPaint.setColor(color_title);
        String title = "血压测量报告";
        canvas.drawText(title, allWidth / 2 - (titleSize * title.length() / 2),
                startY, textPaint);
        startY += titleSize;
        textPaint.setTextSize(textSize);
        if ("右".equals(hand)) {
            hand = "右臂";
        } else {
            hand = "左臂";
        }
        canvas.drawText("测量位置：" + hand, startX, startY, textPaint);
        startY += textSize;
        canvas.drawText("收缩压：" + sbp, startX, startY, textPaint);
        startY += textSize;
        canvas.drawText("舒张压：" + dbp, startX, startY, textPaint);
        startY += textSize;
        canvas.drawText("脉率：" + pulse, startX, startY, textPaint);
        startY += textSize;
        textPaint.setTextSize(38);
        canvas.drawText("测量时间：" + xueyaTime, startX, startY, textPaint);
        startY += textSize;
        startY += textSize;
        startY += textSize;
        return startY;
    }

    public static int drawXuezhi(Canvas canvas, int startX, int startY,
                                 String sbp, String dbp, String pulse, String xueyaTime, String hand) {
        int allWidth = canvas.getWidth();
        int allHeight = canvas.getHeight();
        Paint textPaint = new Paint();
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL);
        int titleSize = 60;
        int textSize = 48;
        textPaint.setTextSize(titleSize);
        textPaint.setColor(color_title);
        String title = "血压测量报告";
        canvas.drawText(title, allWidth / 2 - (titleSize * title.length() / 2),
                startY, textPaint);
        startY += titleSize;
        textPaint.setTextSize(textSize);
        if ("右".equals(hand)) {
            hand = "右臂";
        } else {
            hand = "左臂";
        }
        canvas.drawText("测量位置：" + hand, startX, startY, textPaint);
        startY += textSize;
        canvas.drawText("收缩压：" + sbp, startX, startY, textPaint);
        startY += textSize;
        canvas.drawText("舒张压：" + dbp, startX, startY, textPaint);
        startY += textSize;
        canvas.drawText("脉率：" + pulse, startX, startY, textPaint);
        startY += textSize;
        textPaint.setTextSize(38);
        canvas.drawText("测量时间：" + xueyaTime, startX, startY, textPaint);
        startY += textSize;
        startY += textSize;
        startY += textSize;
        return startY;
    }

    public static int drawXuetang(Canvas canvas, int startX, int startY,
                                  String glu_value, String gluTime, String glu_eat) {
        int allWidth = canvas.getWidth();
        int allHeight = canvas.getHeight();
        Paint textPaint = new Paint();
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL);
        int titleSize = 60;
        int textSize = 48;
        textPaint.setTextSize(titleSize);
        textPaint.setColor(color_title);
        String title = "血糖测量报告";
        canvas.drawText(title, allWidth / 2 - (titleSize * title.length() / 2),
                startY, textPaint);
        startY += titleSize;
        textPaint.setTextSize(textSize);
        if ("后".equals(glu_eat)) {
            glu_eat = "餐后血糖";
        } else {
            glu_eat = "空腹血糖";
        }
        canvas.drawText("测量类型：" + glu_eat, startX, startY, textPaint);
        startY += textSize;
        canvas.drawText("血糖值：" + glu_value, startX, startY, textPaint);
        startY += textSize;
        textPaint.setTextSize(38);
        canvas.drawText("测量时间：" + gluTime, startX, startY, textPaint);
        startY += textSize;
        startY += textSize;
        startY += textSize;
        return startY;
    }

    /***
     * 保存一张尿液的pdf。写到文字中。
     */
    public static void saveNiaoye_Xueya_XuetangPdf(Context context,
                                                   String pdfPath, String pdfName, String name, String sex,
                                                   String yearsold, String checkTime, String glu, String leu,
                                                   String bld, String ph, String pro, String ubg, String nit,
                                                   String sg, String ket, String bil, String vc, String sbp,
                                                   String dbp, String pulse, String xueyaTime, String glu_xuetangyi,
                                                   String xuetangTime, String temp, String tempTime) {
        // 先打开document，然后获取文件流
        Document document = new Document(PageSize.A4);
        document.setPageCount(1);
        try {
            File pdfPathFile = new File(pdfPath);
            if (!pdfPathFile.exists()) {
                pdfPathFile.mkdirs();
            }
            File pdfFile = new File(pdfPathFile, pdfName);
            if (!pdfFile.exists()) {
                pdfFile.createNewFile();
            }
            PdfWriter writer = PdfWriter.getInstance(document,
                    new FileOutputStream(pdfFile));
            writer.setPdfVersion(PdfWriter.VERSION_1_2);
            document.open();
            // 设置标题头
            Font font = getChineseFont(14);
            if (TextUtils.isEmpty(leu) && TextUtils.isEmpty(glu)
                    && TextUtils.isEmpty(pro)) {

            } else {
                Paragraph title = new Paragraph("尿液分析报告\n", getChineseFont(18));
                title.setAlignment(Element.ALIGN_CENTER);// 居中显示
                // 增加病人信息
                document.add(title);
                Paragraph userInfo = new Paragraph("  姓名： " + name
                        + "  性别：    " + sex + "  年龄：" + yearsold + "\n",
                        getChineseFont(16));
                document.add(userInfo);
                document.add(new Paragraph("", getChineseFont(2)));
                // 增加尿液测量的项目参数、数据
                int cellCount = 6;
                PdfPTable table = getNiaoyetable(cellCount);
                font = getChineseFont(14);
                table.addCell(new Paragraph("序号", font));
                table.addCell(new Paragraph("英文代号", font));
                table.addCell(new Paragraph("项目", font));
                table.addCell(new Paragraph("结果", font));
                table.addCell(new Paragraph("单位", font));
                table.addCell(new Paragraph("参考值", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("1", font));
                table.addCell(new Paragraph("glu", font));
                table.addCell(new Paragraph("尿糖", font));
                table.addCell(new Paragraph(glu, font));
                table.addCell(new Paragraph("mmol/L", font));
                // 单位
                table.addCell(new Paragraph("-", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("2", font));
                table.addCell(new Paragraph("leu", font));
                table.addCell(new Paragraph("白细胞", font));
                table.addCell(new Paragraph(leu, font));
                table.addCell(new Paragraph("Cell/uL", font));
                table.addCell(new Paragraph("-", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("3", font));
                table.addCell(new Paragraph("bld", font));
                table.addCell(new Paragraph("潜血", font));
                table.addCell(new Paragraph(bld, font));
                table.addCell(new Paragraph("", font));
                table.addCell(new Paragraph("-", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("4", font));
                table.addCell(new Paragraph("ph", font));
                table.addCell(new Paragraph("酸碱度", font));
                table.addCell(new Paragraph(ph, font));
                table.addCell(new Paragraph("ph", font));
                table.addCell(new Paragraph("6.5-7.5", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("5", font));
                table.addCell(new Paragraph("pro", font));
                table.addCell(new Paragraph("蛋白质", font));
                table.addCell(new Paragraph(pro, font));
                table.addCell(new Paragraph("g/L", font));
                table.addCell(new Paragraph("6.5-7.5", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("6", font));
                table.addCell(new Paragraph("ubg", font));
                table.addCell(new Paragraph("尿胆原", font));
                table.addCell(new Paragraph(ubg, font));
                table.addCell(new Paragraph("umol/L", font));
                table.addCell(new Paragraph("3-16umol/L", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("7", font));
                table.addCell(new Paragraph("nit", font));
                table.addCell(new Paragraph("亚硝酸盐", font));
                table.addCell(new Paragraph(nit, font));
                table.addCell(new Paragraph("", font));
                table.addCell(new Paragraph("-", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("8", font));
                table.addCell(new Paragraph("sg", font));
                table.addCell(new Paragraph("比重", font));
                table.addCell(new Paragraph(sg, font));
                table.addCell(new Paragraph("", font));
                table.addCell(new Paragraph("1.003-1.03", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("9", font));
                table.addCell(new Paragraph("ket", font));
                table.addCell(new Paragraph("尿酮体", font));
                table.addCell(new Paragraph(ket, font));
                table.addCell(new Paragraph("mmol/L", font));
                table.addCell(new Paragraph("-", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("10", font));
                table.addCell(new Paragraph("bil", font));
                table.addCell(new Paragraph("胆红素", font));
                table.addCell(new Paragraph(bil, font));
                table.addCell(new Paragraph("umol/L", font));
                table.addCell(new Paragraph("-", font));
                document.add(table);

                table = getNiaoyetable(cellCount);
                table.addCell(new Paragraph("11", font));
                table.addCell(new Paragraph("vc", font));
                table.addCell(new Paragraph("维生素C", font));
                table.addCell(new Paragraph(vc, font));
                table.addCell(new Paragraph("mmol/L", font));
                table.addCell(new Paragraph("-", font));
                document.add(table);
                Paragraph time = new Paragraph("测量时间：" + checkTime, font);
                time.setAlignment(Element.ALIGN_RIGHT);
                document.add(time);
            }
            // 增加一个换行的。
            Paragraph huanhang = new Paragraph(" \n", font);
            document.add(huanhang);
            if (!TextUtils.isEmpty(dbp)) {
                Paragraph xueya_Title = new Paragraph("血压测量报告\n",
                        getChineseFont(18));
                xueya_Title.setAlignment(Element.ALIGN_CENTER);// 居中显示
                document.add(xueya_Title);
                Paragraph sbp_ph = new Paragraph("  收缩压：" + sbp,
                        getChineseFont(14));
                document.add(sbp_ph);
                Paragraph dbp_ph = new Paragraph("  舒张压：" + dbp,
                        getChineseFont(14));
                document.add(dbp_ph);
                Paragraph pulse_ph = new Paragraph("  脉率：" + pulse,
                        getChineseFont(14));
                document.add(pulse_ph);
                Paragraph xueyaTime_Ph = new Paragraph("测量时间：" + xueyaTime,
                        font);
                xueyaTime_Ph.setAlignment(Element.ALIGN_RIGHT);
                document.add(xueyaTime_Ph);
            }
            if (!TextUtils.isEmpty(glu_xuetangyi)) {
                Paragraph xuetang_Title = new Paragraph("血糖测量报告\n",
                        getChineseFont(18));
                xuetang_Title.setAlignment(Element.ALIGN_CENTER);// 居中显示
                document.add(xuetang_Title);
                Paragraph glu_Ph = new Paragraph("  血糖值：" + glu_xuetangyi,
                        getChineseFont(14));
                document.add(glu_Ph);
                Paragraph xuetangTime_Ph = new Paragraph("测量时间：" + xuetangTime,
                        font);
                xuetangTime_Ph.setAlignment(Element.ALIGN_RIGHT);
                document.add(xuetangTime_Ph);
            }
            if (!TextUtils.isEmpty(temp)) {
                Paragraph temp_Title = new Paragraph("体温测量报告\n",
                        getChineseFont(18));
                temp_Title.setAlignment(Element.ALIGN_CENTER);// 居中显示
                document.add(temp_Title);
                Paragraph temp_Ph = new Paragraph("  血糖值：" + temp,
                        getChineseFont(14));
                document.add(temp_Ph);
                Paragraph tempTime_Ph = new Paragraph("测量时间：" + tempTime, font);
                tempTime_Ph.setAlignment(Element.ALIGN_RIGHT);
                document.add(tempTime_Ph);
            }

            document.close();
            Intent intent = new Intent();
            // ComponentName comp = new ComponentName(
            // "com.dynamixsoftware.printershare",
            // "com.dynamixsoftware.printershare.ActivityPrintPDF");
            // intent.setComponent(comp);
            intent.setAction("android.intent.action.VIEW");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf");
            intent.putExtra("scaleFitToPage", true);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    /***
     * 保存一张尿液的pdf。写到文字中。
     *
     * @return
     */
    public static boolean saveNiaoye_Xueya_XuetangBitmap(Context context,
                                                         String pngPath, String pngFileName, String idCard,
                                                         String hospitalName, String name, String sex, String yearsold,
                                                         String checkTime, String glu, String leu, String bld, String ph,
                                                         String pro, String ubg, String nit, String sg, String ket,
                                                         String bil, String vc, String sbp, String dbp, String pulse,
                                                         String xueyaTime, String hand, String glu_xuetangyi,
                                                         String xuetangTime, String glu_eat, String temp, String tempTime) {
        Bitmap bitmap = Bitmap
                .createBitmap(1758, 2500, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        int startY = 220;
        int startX = 200;
        // 分别保存尿液、血压、血糖到一张纸上。
        canvas.drawColor(Color.WHITE);
        startY = drawUserInfo(canvas, startX, startY, name, sex, yearsold,
                hospitalName, idCard);
        if (!TextUtils.isEmpty(glu) && !TextUtils.isEmpty(leu)) {
            startY = drawNiaoye(canvas, startX, startY, name, sex, yearsold,
                    checkTime, glu, leu, bld, ph, pro, ubg, nit, sg, ket, bil,
                    vc);
        }
        if (!TextUtils.isEmpty(sbp) && !TextUtils.isEmpty(dbp)) {
            startY = drawXueya(canvas, startX, startY, sbp, dbp, pulse,
                    xueyaTime, hand);
        }
        if (!TextUtils.isEmpty(xuetangTime)
                && !TextUtils.isEmpty(glu_xuetangyi)) {
            startY = drawXuetang(canvas, startX, startY, glu_xuetangyi,
                    xuetangTime, glu_eat);
        }
        if (!TextUtils.isEmpty(temp)) {
            drawTiwen(canvas, startX, startY, temp, tempTime);
        }
        return saveBitmap(bitmap, pngPath, pngFileName);
        // File file = new File(getSDCardPath() + "/bitmap2pdf.pdf");
        // if (!file.exists()) {
        // try {
        // file.createNewFile();
        // } catch (IOException e) {
        // e.printStackTrace();
        // }
        // savePDFFile("", bitmap, getSDCardPath() + "/bitmap2pdf.pdf");
        // }
    }

    public static void pdf2png(String pdfFile, String pngFile) {
        PdfReader pdf;
        try {
            // new
            // File(getSDCardPath()+"/心电打印文档图片缓存/TT","2016-11-18T17+52+15.00.png");
            pdf = new PdfReader(getSDCardPath() + "/TT/2016-11-1817:56:39.pdf");
            PdfStamper stp = new PdfStamper(pdf, new FileOutputStream(
                    getSDCardPath() + "/TT/jiuminga.pdf"));
            PdfWriter writer = stp.getWriter();
            File pngfile = new File(getSDCardPath() + "/TT", "aiaiai.png");
            if (!pngfile.exists()) {
                pngfile.createNewFile();
            }
            Image img = Image.getInstance("aiaiai.png");
            PdfDictionary pg = pdf.getPageN(1);
            PdfDictionary res = (PdfDictionary) PdfReader.getPdfObject(pg
                    .get(PdfName.RESOURCES));
            PdfDictionary xobj = (PdfDictionary) PdfReader.getPdfObject(res
                    .get(PdfName.XOBJECT));
            if (xobj != null) {
                for (Iterator it = xobj.getKeys().iterator(); it.hasNext(); ) {
                    PdfObject obj = xobj.get((PdfName) it.next());
                    if (obj.isIndirect()) {
                        PdfDictionary tg = (PdfDictionary) PdfReader
                                .getPdfObject(obj);
                        PdfName type = (PdfName) PdfReader.getPdfObject(tg
                                .get(PdfName.SUBTYPE));
                        if (PdfName.IMAGE.equals(type)) {
                            PdfReader.killIndirect(obj);
                            Image maskImage = img.getImageMask();
                            if (maskImage != null)
                                writer.addDirectImageSimple(maskImage);
                            writer.addDirectImageSimple(img,
                                    (PRIndirectReference) obj);
                            break;
                        }
                    }
                }
            }
            stp.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static PdfPTable getNiaoyetable(int cellCount) {
        PdfPTable table = new PdfPTable(cellCount);
        // table.setHorizontalAlignment(90);
        table.setWidthPercentage(100);
        return table;
    }

    /**
     * 保存一张心电的图片。
     */
    public static void saveEcgPNG(String pngPath, String pngName,
                                  int[] report1, String name, String sex, String idCard, String age,
                                  String checkTime, String result, String hospital,
                                  ArrayList<int[]> ecgDatas) {
        Bitmap bitmap = Bitmap
                .createBitmap(2500, 1758, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        // 文字区域0-11 图片区域11-43;
        drawBackGround(canvas);
        if (checkTime.endsWith(".00")) {
            checkTime = checkTime.substring(0, checkTime.length() - 3);
        }
        checkTime = checkTime.replace("T", " ");
        drawECGResult(canvas, report1, name, sex, age, checkTime, idCard,
                result, hospital);
        drawECGValue(ecgDatas, canvas);
        saveBitmap(bitmap, pngPath, pngName);
    }

    /***
     *
     * @param bitmap
     *            bitmap
     * @param filePath
     *            文件保存的路径
     * @param fileName
     *            文件保存的名称 xxx.bmp xxx.png xxx.jpg
     */
    public static boolean saveBitmap(Bitmap bitmap, String filePath,
                                     String fileName) {
        FileOutputStream fos;

        try {
            File path = new File(filePath);
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File(filePath, fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            // FileSaveUtil.savePDFFile("姓名 \n", myScreenBitmap,
            // pdfFileName);
            // FileSaveUtil.savePDFFile("姓名是\n", file.getAbsolutePath(),
            // pdfFileName);
            fos.close();
            return true;
        } catch (FileNotFoundException e) {
            Log.e("Panel", "FileNotFoundException", e);
            return false;
        } catch (IOException e) {
            Log.e("Panel", "IOEception", e);
            return false;
        }
    }

    /***
     * 网格的颜色。由于黄色的，用黑白打印不出来。
     */
    private static int color_wangge = Color.BLACK;
    /***
     * 标题的颜色。原来是浅蓝色的，但是黑白打印不出来，所以改为黑色的。
     */
    private static int color_title = Color.BLACK;

    private static void drawBackGround(Canvas canvas) {
        int allWidth = canvas.getWidth(), allHeight = canvas.getHeight();
        // 图片的宽度
        int picWidth = allWidth;
        // 图片的高度
        int picHeight = allHeight / 43 * (43 - 11) - 48;
        /********** 画网格 **********/
        Paint mPaint = new Paint();
        mPaint.setColor(color_wangge);
        mPaint.setStrokeWidth(2);
        canvas.drawColor(Color.WHITE);
        int height = canvas.getHeight();
        int width = canvas.getWidth();
        // 一共多少个大格子，就是多少厘米
        int geziCount = 27;
        // 1mm代表的宽度
        int mm1 = allWidth / (geziCount * 10);
        System.out.println("mm1的长度是：" + mm1);
        // 每隔5mm就画一线
        int mmH = mm1 * 5;
        // y轴空白的高度，就是从上到下哪里开始画图。
        int startDrawY = allHeight - picHeight;
        for (int u = 0; u < (width + mm1); u += mm1) {
            if (u % mmH == 0) {
                canvas.drawLine(u, startDrawY, u, height, mPaint); // 纵轴方向
                // 每隔30px即5mm
            } else {
                // 纵轴方向每隔6px打点即1mm
                for (int i = 0; i < (height + mm1); i += mm1)
                    canvas.drawPoint(u, startDrawY + i, mPaint);
            }
        }
        for (int v = 0; v < (height + mmH) / mmH; v++) {
            canvas.drawLine(0, +startDrawY + v * mmH, width, startDrawY + v
                    * mmH, mPaint);
        }
        // 导联I和导联II的Y轴上下间隔。
        int jiangeY = picHeight / 4;
        int jiangeX = picWidth / 4;
        // startDrawY开始的Y
        /********** 添加说明 **********/
        Paint textPaint = new Paint();
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setTextSize(36);
        // 从左边x开始baseX；
        int baseX = 0;
        startX1 = baseX;
        startY1 = startDrawY + jiangeY / 2;
        startX2 = baseX;
        startY2 = startY1 + jiangeY;
        startX3 = baseX;
        startY3 = startY2 + jiangeY;
        startX22 = baseX;
        startY22 = startY3 + jiangeY;

        startXvr = baseX + jiangeX;
        startYvr = startDrawY + jiangeY / 2;
        startXvl = baseX + jiangeX;
        startYvl = startY1 + jiangeY;
        startXvf = baseX + jiangeX;
        startYvf = startY2 + jiangeY;

        startXv1 = baseX + jiangeX * 2;
        startYv1 = startDrawY + jiangeY / 2;
        startXv2 = baseX + jiangeX * 2;
        startYv2 = startY1 + jiangeY;
        startXv3 = baseX + jiangeX * 2;
        startYv3 = startY2 + jiangeY;

        startXv4 = baseX + jiangeX * 3;
        startYv4 = startDrawY + jiangeY / 2;
        startXv5 = baseX + jiangeX * 3;
        startYv5 = startY1 + jiangeY;
        startXv6 = baseX + jiangeX * 3;
        startYv6 = startY2 + jiangeY;

        // startDrawX空白的开始画图的地方
        canvas.drawText("I", startX1, startY1, textPaint);
        canvas.drawText("II", startX2, startY2, textPaint);
        canvas.drawText("III", startX3, startY3, textPaint);
        canvas.drawText("II", startX22, startY22, textPaint);
        canvas.drawText("aVR", startXvr, startYvr, textPaint);
        canvas.drawText("aVL", startXvl, startYvl, textPaint);
        canvas.drawText("aVF", startXvf, startYvf, textPaint);
        canvas.drawText("V1", startXv1, startYv1, textPaint);
        canvas.drawText("V2", startXv2, startYv2, textPaint);
        canvas.drawText("V3", startXv3, startYv3, textPaint);
        canvas.drawText("V4", startXv4, startYv4, textPaint);
        canvas.drawText("V5", startXv5, startYv5, textPaint);
        canvas.drawText("V6", startXv6, startYv6, textPaint);
    }

    static int startX1;
    static int startY1;
    static int startX2;
    static int startY2;
    static int startX3;
    static int startY3;
    static int startX22;
    static int startY22;

    static int startXvr;
    static int startYvr;
    static int startXvl;
    static int startYvl;
    static int startXvf;
    static int startYvf;

    static int startXv1;
    static int startYv1;
    static int startXv2;
    static int startYv2;
    static int startXv3;
    static int startYv3;

    static int startXv4;
    static int startYv4;
    static int startXv5;
    static int startYv5;
    static int startXv6;
    static int startYv6;

    private static void drawECGResult(Canvas canvas, int[] report1,
                                      String name, String sex, String age, String checkTime,
                                      String idCard, String result, String hospital) {
        int allWidth = canvas.getWidth(), allHeight = canvas.getHeight();
        // 图片的宽度
        int picWidth = allWidth;
        Paint textPaint = new Paint();
        int textSize = 48;
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setTextSize(textSize);
        textPaint.setColor(color_title);
        // 下一个开始的x位置，就是上面已经画好的，然后从nextStartX开始画
        int nextStartY = 0;
        idCard = idCard.substring(0, idCard.length() - 8) + "****"
                + idCard.substring(idCard.length() - 4, idCard.length());
        canvas.drawText(checkTime + " ID:" + idCard + " 性别：" + sex + " 年龄："
                        + age + " 姓名：" + name + "  医院名称：" + hospital, 0, textSize,
                textPaint);
        canvas.drawLine(0, textSize + 6, allWidth, textSize + 6, textPaint);
        nextStartY = textSize + 6 + textSize;
        textPaint.setColor(Color.BLACK);
        canvas.drawText("**分析报告** [未确定报告，需医生确认：_ _ _ _ _]", 100, nextStartY,
                textPaint);
        nextStartY += textSize;
        int firstWidth = 300;
        int dataWidth = 450;
        int secondWidth = 800;
        int resultWidth = 950;
        String hr = report1[0] + "";
        String pr_jq = report1[1] / 10 + "";
        String qrs_sx = report1[2] / 10 + "";
        String qt_jq = report1[3] / 10 + "";
        String qtc_jq = report1[4] / 10 + "";
        String p_dz = report1[5] / 10 + "";
        String qrs_dz = report1[6] / 10 + "";
        String t_dz = report1[7] / 10 + "";
        String rv5_dy = report1[8] / 100 + "";
        String sv1_dy = report1[9] / 100 + "";
        String rv5addsv1 = report1[8] / 100 + report1[9] / 100 + "";

        canvas.drawText("HR ", 0, nextStartY, textPaint);
        canvas.drawText("心率", firstWidth, nextStartY, textPaint);
        canvas.drawText(hr, dataWidth, nextStartY, textPaint);
        canvas.drawText("bmp", secondWidth, nextStartY, textPaint);
        String[] results = result.split("\n");
        int tempY = nextStartY;
        for (int i = 0; i < results.length; i++) {
            canvas.drawText(results[i], resultWidth, tempY, textPaint);
            tempY += textSize;
        }
        nextStartY += textSize;
        canvas.drawText("PR ", 0, nextStartY, textPaint);
        canvas.drawText("间期", firstWidth, nextStartY, textPaint);
        canvas.drawText(pr_jq, dataWidth, nextStartY, textPaint);
        canvas.drawText("ms", secondWidth, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("QRS", 0, nextStartY, textPaint);
        canvas.drawText("时限", firstWidth, nextStartY, textPaint);
        canvas.drawText(qrs_sx, dataWidth, nextStartY, textPaint);
        canvas.drawText("ms", secondWidth, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("QT/QTC", 0, nextStartY, textPaint);
        canvas.drawText("间期", firstWidth, nextStartY, textPaint);
        canvas.drawText(qt_jq + "/" + qtc_jq, dataWidth, nextStartY, textPaint);
        canvas.drawText("ms", secondWidth, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("P/QRS/T", 0, nextStartY, textPaint);
        canvas.drawText("电轴", firstWidth, nextStartY, textPaint);
        canvas.drawText(p_dz + "/" + qrs_dz + "/" + t_dz, dataWidth,
                nextStartY, textPaint);
        canvas.drawText("°", secondWidth, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("RV5/SV1", 0, nextStartY, textPaint);
        canvas.drawText("电压", firstWidth, nextStartY, textPaint);
        canvas.drawText(rv5_dy + "/" + sv1_dy, dataWidth, nextStartY, textPaint);
        canvas.drawText("mV", secondWidth, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("RV5+SV1", 0, nextStartY, textPaint);
        canvas.drawText("电压", firstWidth, nextStartY, textPaint);
        canvas.drawText(rv5addsv1, dataWidth, nextStartY, textPaint);
        canvas.drawText("mV", secondWidth, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("  [ 25mm/S ] [ 10mm/mV ]", 0, nextStartY, textPaint);
    }

    /***
     * 画心电图线。
     *
     * @param ecgDatas
     *            集合，每个元素存放一个导联的int数组
     * @param canvas
     */
    private static void drawECGValue(ArrayList<int[]> ecgDatas, Canvas canvas) {
        /********** 画心电图线 **********/
        drawECGGraph(startY1, ecgDatas.get(0), 1, canvas); // I
        drawECGGraph(startY2, ecgDatas.get(1), 2, canvas); // II
        drawECGGraph(startY3, ecgDatas.get(2), 3, canvas); // III
        drawECGGraph(startYvr, ecgDatas.get(3), 4, canvas); // aVR
        drawECGGraph(startYvl, ecgDatas.get(4), 5, canvas); // aVL
        drawECGGraph(startYvf, ecgDatas.get(5), 6, canvas); // aVF
        drawECGGraph(startYv1, ecgDatas.get(6), 7, canvas); // v1
        drawECGGraph(startYv2, ecgDatas.get(7), 8, canvas); // v2
        drawECGGraph(startYv3, ecgDatas.get(8), 9, canvas); // v3
        drawECGGraph(startYv4, ecgDatas.get(9), 10, canvas); // v4
        drawECGGraph(startYv5, ecgDatas.get(10), 11, canvas); // v5
        drawECGGraph(startYv6, ecgDatas.get(11), 12, canvas); // v6
        drawECGGraph(startY22, ecgDatas.get(1), 22, canvas); // II的。最后一条
    }

    public static double xWidth = 0.9;

    private static final float gain = 0.32f;

    private static void drawECGGraph(int base, int[] ecgDatas, int tag,
                                     Canvas canvas) {
        Paint mPaint = new Paint();
        mPaint.setColor(Color.BLACK);
        mPaint.setStrokeWidth(2);
        ArrayList<Integer> oneList = null;
        int maxCount = ecgDatas.length / 4 - 10;
        float baseX;
        switch (tag) {
            case 1:
                oneList = new ArrayList<Integer>();
                baseX = startX1 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
            case 2:
                oneList = new ArrayList<Integer>();
                baseX = startX2 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 3:
                oneList = new ArrayList<Integer>();
                baseX = startX3 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 4:
                oneList = new ArrayList<Integer>();
                baseX = startXvr + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 5:
                oneList = new ArrayList<Integer>();
                baseX = startXvl + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 6:
                oneList = new ArrayList<Integer>();
                baseX = startXvf + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 7:
                oneList = new ArrayList<Integer>();
                baseX = startXv1 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 8:
                oneList = new ArrayList<Integer>();
                baseX = startXv2 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 9:
                oneList = new ArrayList<Integer>();
                baseX = startXv3 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 10:
                oneList = new ArrayList<Integer>();
                baseX = startXv4 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 11:
                oneList = new ArrayList<Integer>();
                baseX = startXv5 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 12:
                oneList = new ArrayList<Integer>();
                baseX = startXv6 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 22:
                oneList = new ArrayList<Integer>();
                baseX = startX22 + 20;
                maxCount = ecgDatas.length;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 根据int[]数组的幅度值，来获取
     *
     * @param base
     * @param y
     * @return
     */
    private static int convertY2Pix(int base, int y) {
        // 60/160=0.375
        double newValue = base + (-(y) * 0.667 * gain);
        int value = newValue >= 0 ? (int) (newValue + 0.5)
                : (int) (newValue - 0.5);
        // Log.i("value", "base =" + base + " " + "value =" + "" + value);
        return value;
    }

    /***
     * 获取自定义字号的中文字体
     *
     * @param textSize
     * @return
     */
    public static Font getChineseFont(int textSize) {
        BaseFont bf = null;
        Font fontChinese = null;
        try {
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            fontChinese = new Font(bf, textSize, Font.NORMAL, BaseColor.BLACK);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fontChinese;
    }

    /***
     * 默认12号的中文字体。
     *
     * @return
     */
    public static Font getChineseFont() {
        BaseFont bf = null;
        Font fontChinese = null;
        try {
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);

            fontChinese = new Font(bf, 12, Font.NORMAL);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fontChinese;
    }

    private static byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

    // 产生PDF字体
    public static Font setChineseFont() {
        BaseFont bf = null;
        Font fontChinese = null;
        try {
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            fontChinese = new Font(bf, 12, Font.NORMAL);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fontChinese;
    }

    public static boolean savePDFFile(String textContent, Bitmap bitmap,
                                      String filePath) {
        Document document = new Document(PageSize.A4.rotate(), 5, 5, 5, 5);
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            PdfWriter.getInstance(document, fos);
            // step 3: we open the document
            document.open();
            // step 4:
            // document.add(new Paragraph(textContent));
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            // Bitmap bitmap2 = small(bitmap);
            // Bitmap bitmap = resizeBitMapImage1(pngPath, 720, 480);
            bitmap.compress(Bitmap.CompressFormat.PNG /* FileType */,
                    100 /* Ratio */, stream);
            Image jpg = Image.getInstance(stream.toByteArray());
            jpg.scalePercent(0.65f);
            // Image jpg = Image.getInstance(pngPath);
            jpg.setAlignment(Image.MIDDLE);
            // document.add(jpg);
            document.close();
        } catch (Exception e) {
            System.out.println("保存打印文件失败。。。");
            e.printStackTrace();
        }
        return true;
    }

    private static Bitmap small(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.62f, 0.62f); // 长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

    private static Bitmap small(Bitmap bitmap, float sx, float sy) {
        Matrix matrix = new Matrix();
        matrix.postScale(sx, sy); // 长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

    public static Bitmap big(Bitmap b, float x, float y) {
        int w = b.getWidth();
        int h = b.getHeight();
        float sx = (float) x / w;// 要强制转换，不转换我的在这总是死掉。
        float sy = (float) y / h;
        Matrix matrix = new Matrix();
        matrix.postScale(sx, sy); // 长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(b, 0, 0, w, h, matrix, true);
        return resizeBmp;
    }

    public static Bitmap resizeBitMapImage1(String filePath, int targetWidth,
                                            int targetHeight) {
        Bitmap bitMapImage = null;
        // First, get the dimensions of the image
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        double sampleSize = 0;
        // Only scale if we need to
        // (16384 buffer for img processing)
        Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
                .abs(options.outWidth - targetWidth);
        if (options.outHeight * options.outWidth * 2 >= 1638) {
            // Load, scaling to smallest power of 2 that'll get it <= desired
            // dimensions
            sampleSize = scaleByHeight ? options.outHeight / targetHeight
                    : options.outWidth / targetWidth;
            sampleSize = (int) Math.pow(2d,
                    Math.floor(Math.log(sampleSize) / Math.log(2d)));
        }
        // Do the actual decoding
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[128];
        while (true) {
            try {
                options.inSampleSize = (int) sampleSize;
                bitMapImage = BitmapFactory.decodeFile(filePath, options);
                break;
            } catch (Exception ex) {
                try {
                    sampleSize = sampleSize * 2;
                } catch (Exception ex1) {
                }
            }
        }
        return bitMapImage;
    }

    /***
     * 获取assets中的txt文件的字符串数据
     *
     * @param context
     * @param fileName
     * @return txt的字符串数据
     */
    /*
     * public static int[] getAssetsString(Context context, String fileName) {
	 * String result = ""; InputStream inputStream; StringBuilder sb = null; try
	 * { inputStream = context.getResources().getAssets().open(fileName);
	 * InputStreamReader inputStreamReader; inputStreamReader = new
	 * InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader =
	 * new BufferedReader( inputStreamReader); String line = ""; sb = new
	 * StringBuilder(); int s = bufferedReader.read(); System.out.println(s);
	 * while ((line = bufferedReader.readLine()) != null) { sb.append(line); }
	 * sb.toString(); } catch (IOException e) { e.printStackTrace(); } return
	 * string2Ints(sb.toString()); }
	 */

    /***
     * 将字符串转化为一个int数组。
     *
     * @param intsString
     * @return 返回一个int数组
     */
    public static int[] string2Ints(String intsString) {
        if (intsString == null) {
            intsString = "";
        }
        String[] strArray = intsString.trim().split(",");
        int[] result = new int[strArray.length];
        for (int i = 0; i < strArray.length; i++) {
            result[i] = Integer.parseInt(strArray[i]);
        }
        return result;
    }

    /***
     * 获取用来展示的心电假数据
     *
     * @param context
     * @return
     */
    /*
     * public static ArrayList<int[]> getShowECGDatas(Context context) {
	 * ArrayList<int[]> result = new ArrayList<int[]>(); for (int i = 0; i < 12;
	 * i++) { int[] temp = getAssetsString(context, "ecg/导联" + i + ".txt");
	 * result.add(temp); } return result; }
	 */
}
